<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.PlanName"
        placeholder="输入名称查询"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="正在发布中，请不要做其他操作，也不要关闭和刷新页面"
      :data="list"
      border
      fit
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="Id"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.planName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划类型" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.workType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行周期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.execDuring }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行开始日期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.execBeginDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行截止日期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.execEndDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近发布日期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.planLastPublishDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板ID" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.templateID }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.templateName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否已被发布" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.releaseStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划描述" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.planDescribe }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="270">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            style="margin-right: 10px"
            size="mini"
            @click="handOpenList(row)"
          >
            配置站点
          </el-button>
          <el-popconfirm title="确定发布?" @onConfirm="handlePush(row)">
            <el-button
              slot="reference"
              type="primary"
              size="mini"
              :disabled="row.releaseStatus == '是'"
            >
              发布
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[20]"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :width="'800px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :inline="true"
        :model="temp"
        label-width="120px"
        style="margin-right: 20px"
      >
        <el-form-item label="计划名称" prop="planName">
          <el-input
            v-model="temp.planName"
            :disabled="dialogStatus === 'create' ? false : true"
          />
        </el-form-item>
        <el-form-item label="计划类型" prop="计划类型">
          <el-select v-model="temp.workType">
            <el-option
              v-for="item in planTypes"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行周期" prop="execDuring">
          <el-select v-model="temp.execDuring">
            <el-option
              v-for="item in execDurings"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="最近发布日期">
          <el-input v-model="temp.planLastPublishDate" />
        </el-form-item>
        <el-form-item v-if="temp.execDuring == '临时'" label="执行开始日期">
          <el-date-picker
            v-model="temp.execBeginDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item v-if="temp.execDuring == '临时'" label="执行截止日期">
          <el-date-picker
            v-model="temp.execEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          v-if="temp.execDuring == '月度' || temp.execDuring == '季度'"
          label="执行开始日期"
        >
          <el-select v-model="temp.execBeginDate">
            <el-option
              v-for="item in dates"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称">
          <el-select
            v-model="temp.templateName"
            value-key="templateName"
            @change="onTempChange"
          >
            <el-option
              v-for="item in tempOptions"
              :key="item.templateName"
              :label="item.templateName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板ID">
          <el-input v-model="temp.templateID" disabled />
        </el-form-item>
        <el-form-item label="计划描述">
          <el-input
            v-model="temp.planDescribe"
            type="textarea"
            rows="4"
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 关闭 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="配置站点"
      :visible.sync="dialogSetVisible"
      :width="'800px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-if="dialogSetVisible">
        <el-row>
          <el-button type="primary" @click="openAdd">新增站点</el-button>
          <el-button type="primary" @click="openLoad">导入站点</el-button>
        </el-row>
        <div class="filter-container" style="margin-top: 10px">
          <el-input
            v-model="listPlanSiteQuery.siteName"
            placeholder="输入站址名称"
            style="width: 170px"
            class="filter-item"
            @keyup.enter.native="handleFilter1"
          />
          <el-input
            v-model="listPlanSiteQuery.siteCode"
            placeholder="输入站址编码"
            style="width: 170px"
            class="filter-item"
            @keyup.enter.native="handleFilter1"
          />
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter1"
          >
            查询
          </el-button>
        </div>
        <el-table
          :key="tableKey"
          :data="sitePlanList"
          :height="300"
          border
          fit
          style="width: 100%"
          highlight-current-row
        >
          <el-table-column label="站址名称" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.siteName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="站址编码" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.siteCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="站址运维ID" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.siteMaintanceid }}</span>
            </template>
          </el-table-column>
          <el-table-column label="巡检人员" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.inspectorLoginName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="100"
          >
            <template slot-scope="{ row, $index }">
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteSite(row, $index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="siteTotal > 0"
          :total="siteTotal"
          :page-sizes="[20]"
          :page.sync="listSiteQuery.currentPage"
          :limit.sync="listSiteQuery.limit"
          @pagination="getPlanSiteList"
        />

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSetVisible = false"> 关闭 </el-button>
          <!-- <el-button type="primary" @click="onCreateSite">
          提交
        </el-button> -->
        </div>
      </div>
    </el-dialog>

    <el-dialog
      title="站点列表"
      :visible.sync="dialogSiteVisible"
      :width="'800px'"
      :before-close="onClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-if="dialogSiteVisible">
        <div class="filter-container">
          <el-input
            v-model="listSiteQuery.siteName"
            placeholder="输入站址名称"
            style="width: 170px"
            class="filter-item"
            @keyup.enter.native="handleFilter2"
          />
          <el-input
            v-model="listSiteQuery.siteCode"
            placeholder="输入站址编码"
            style="width: 170px"
            class="filter-item"
            @keyup.enter.native="handleFilter2"
          />
          <el-input
            v-model="listSiteQuery.siteMaintanceID"
            placeholder="输入运维ID"
            style="width: 170px"
            class="filter-item"
            @keyup.enter.native="handleFilter2"
          />
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter2"
          >
            查询
          </el-button>
        </div>
        <el-table
          :key="tableKey"
          :data="siteList"
          :height="300"
          border
          fit
          style="width: 100%"
          highlight-current-row
        >
          <el-table-column label="站址名称" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.siteName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="站址编码" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.siteCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="站址运维ID" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.siteMaintanceid }}</span>
            </template>
          </el-table-column>
          <el-table-column label="巡检人员" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.inspectorLoginName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="170"
          >
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="onCreateSite(row)">
                添加
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="siteTotal > 0"
          :total="siteTotal"
          :page-sizes="[20]"
          :page.sync="listSiteQuery.currentPage"
          :limit.sync="listSiteQuery.limit"
          @pagination="getSiteList"
        />

        <div slot="footer" class="dialog-footer">
          <el-button @click="onClose"> 关闭 </el-button>
          <!-- <el-button type="primary" @click="onCreateSite">
          提交
        </el-button> -->
        </div>
      </div>
    </el-dialog>

    <el-dialog
      v-loading="loading"
      title="巡检对象导入"
      :visible.sync="dialogLoadVisible"
      :width="'800px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      element-loading-text="正在导入中，请不要做其他操作，也不要关闭和刷新页面"
    >
      <div>
        <div>在导入文件之前，请您认真阅读以下注意事项！</div>
        <el-row class="text-line">1.导入文件必须为.xls的excel文件</el-row>
        <el-row
          class="text-line"
        >2.站址运维ID,站址名称不能为空空，代维人员没有导入权限</el-row>
        <el-row
          class="text-line"
        >3.如果提示有空白行，请选择数据下面的空白行删除并清除数据</el-row>
        <el-row
          class="text-line"
        >4.数据尽量不要超过1500条，如果太多可以分批导入，点击导入之后成功之后会有提示信息，请耐心等待</el-row>
      </div>
      <div style="margin-top: 20px">
        <el-upload
          v-if="dialogLoadVisible"
          ref="upload"
          :headers="headers"
          :action="actionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :auto-upload="false"
          :on-success="onUploadSuccess"
          :limit="1"
          name="filename"
        >
          <el-button
            slot="trigger"
            size="small"
            type="primary"
          >选取文件</el-button>
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
          >上传到服务器</el-button>
          <el-button
            style="margin-left: 10px"
            size="small"
          ><a
            href="TaskPlan_ImportSites-模板.xlsx"
            download
          >下载模板</a></el-button>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-input
          v-model="voBatch.successMsg"
          type="textarea"
          :readonly="true"
          :autosize="{ minRows: 1, maxRows: 4 }"
          placeholder="成功导入条数"
        />
        <el-input
          v-model="voBatch.failMsg"
          style="margin-top: 10px"
          :readonly="true"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 4 }"
          placeholder="未功导入条数"
        />
        <el-input
          v-model="voBatch.errorMsg"
          style="margin-top: 10px"
          :readonly="true"
          type="textarea"
          :disabled="false"
          :autosize="{ minRows: 4, maxRows: 4 }"
          placeholder="未成功导入信息"
        />
        <el-button style="margin-top: 10px" @click="dialogLoadVisible = false">
          关闭
        </el-button>
        <!-- <el-button type="primary" @click="onCreateSite">
          提交
        </el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createArticle,
  updateArticle,
  deleteArticle,
} from '@/api/task-plan'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import { fetchList as fetchTempList } from '@/api/temp'
import { fetchList as fetchSiteList } from '@/api/site'
import {
  createArticle as createTaskSite,
  deleteArticle as deletePlanSite,
} from '@/api/task-site'
import {
  // createArticle as createRelease,
  fetchPlanSiteList,
} from '@/api/release'
import { getToken } from '@/utils/auth'
import axios from 'axios'

const ywTypes = [
  { key: '采集', display_name: '采集' },
  { key: '核查', display_name: '核查' },
]
const dxTypes = [{ key: '1', display_name: '机房及配套' }]
const execDurings = [
  { key: '临时', display_name: '临时' },
  { key: '月度', display_name: '月度' },
  { key: '季度', display_name: '季度' },
]
const planTypes = [{ key: '机房设备核查', display_name: '机房设备核查' }]

export default {
  name: 'Polling',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      visible: false,
      tableKey: 0,
      list: null,
      voBatch: {},
      loading: false,
      siteList: [],
      headers: {
        Authorization: getToken(),
      },
      total: 0,
      siteTotal: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
      },
      listSiteQuery: {
        currentPage: 1,
      },
      listPlanSiteQuery: {
        currentPage: 1,
      },
      currentRow: null,
      ywTypes,
      dxTypes,
      execDurings,
      planTypes,
      temp: {},
      dialogFormVisible: false,
      dialogSiteVisible: false,
      dialogSetVisible: false,
      dialogLoadVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
      },
      rules: {
        templateName: [
          { required: true, message: '必填项', trigger: 'change' },
        ],
        includeModuleNames: [
          { required: true, message: '必填项', trigger: 'change' },
        ],
      },
      format: 'yyyy-MM-dd',
      dates: [],
      tempOptions: [],
      currentPlan: null,
      fileList: [],
      actionUrl: '',
      sitePlanList: [],
    }
  },
  computed: {
    ...mapGetters(['loginName']),
  },
  created() {
    this.getList()
    fetchTempList().then((res) => {
      this.tempOptions = res.data.records
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleFilter1() {
      this.listPlanSiteQuery.page = 1
      this.getPlanSiteList()
    },
    handleFilter2() {
      this.listSiteQuery.page = 1
      this.getSiteList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.initDateList()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.templateName = this.temp.templateName?.templateName
          createArticle(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let tempData = Object.assign({}, this.temp)
          tempData = {
            ...tempData,
            templateName: tempData.templateName?.templateName,
          }
          updateArticle(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('保存成功')
          })
        }
      })
    },
    notifyMessage(info) {
      this.$notify({
        title: info,
        type: 'success',
        duration: 2000,
      })
    },
    failNotifyMessage(info) {
      this.$notify({
        title: info,
        type: 'fail',
        duration: 2000,
      })
    },
    handleDelete(row, index) {
      deleteArticle({ planName: row.planName }).then(() => {
        this.getList()
        this.notifyMessage('删除成功')
      })
    },
    handleDeleteSite(row, index) {
      deletePlanSite({
        maintanceID: row.siteMaintanceid,
        planName: this.currentPlan.planName,
      }).then(() => {
        this.getPlanSiteList()
        this.notifyMessage('删除成功')
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    initDateList() {
      const dates = []
      const newDate = new Date()
      const year = newDate.getFullYear()
      const month = newDate.getMonth() + 1
      for (let i = 0; i < 12; i++) {
        let m = month + i
        if (m > 12) {
          m = m - 12
        }
        if (m < 10) {
          m = '0' + m
        }
        dates.push(`${year}-${m}`)
      }
      this.dates = dates
    },
    onTempChange(item) {
      this.temp.templateID = item.id
    },
    handOpenList(row) {
      this.currentPlan = row
      this.dialogSetVisible = true
      this.getPlanSiteList()
    },
    getPlanSiteList() {
      fetchPlanSiteList({
        ...this.listSiteQuery,
        planName: this.currentPlan.planName,
      }).then((response) => {
        this.sitePlanList = response.data.records
        this.siteTotal = response.data.total
      })
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    onTableSelect(val) {
      this.currentRow = val
    },
    onCreateSite(row) {
      createTaskSite({
        planID: this.currentPlan.id,
        planName: this.currentPlan.planName,
        siteCode: row.siteCode,
        maintanceID: row.siteMaintanceid,
        siteName: row.siteName,
      }).then(() => {
        this.notifyMessage('操作成功')
      })
    },
    handlePush(row) {
      this.listLoading = true
      const data = {
        planID: row.id,
        planName: row.planName,
      }
      // createRelease({
      //   planID: row.id,
      //   planName: row.planName,
      // }).then(() => {
      //   this.listLoading=false
      //   this.getList()
      //   this.notifyMessage('操作成功')
      // })
      axios
        .post(
          process.env.VUE_APP_BASE_API + '/taskInspect/addTaskInspect',
          data,
          { headers: { Authorization: getToken() }}
        )
        .then(
          (res) => {
            this.listLoading = false
            if (res.data.code === 200) {
              this.getList()
              this.notifyMessage('操作成功')
            } else {
              this.listLoading = false
              this.failNotifyMessage(res.data.msg)
            }
          },
          (res) => {
            this.listLoading = false
          }
        )
    },
    openAdd() {
      this.dialogSiteVisible = true
      this.getSiteList()
    },
    getSiteList() {
      fetchSiteList(this.listSiteQuery).then((response) => {
        this.siteList = response.data.records
        this.siteTotal = response.data.total
      })
    },
    onClose() {
      this.dialogSiteVisible = false
      this.getPlanSiteList()
    },
    openLoad() {
      this.dialogLoadVisible = true
      this.voBatch = {}
    },
    submitUpload() {
      this.$nextTick(() => {
        this.actionUrl = `${process.env.VUE_APP_BASE_API}/taskSite/batchImport?planID=${this.currentPlan.id}&planName=${this.currentPlan.planName}&loginName=${this.loginName}`
      })
      setTimeout(() => {
        this.$refs.upload.submit()
        this.loading = true
      }, 0)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    onUploadSuccess(res) {
      this.$refs.upload.clearFiles() // 调用element官方的方法
      if (res.code === 200) {
        this.voBatch = res.data
        this.loading = false
        this.getPlanSiteList()
        this.notifyMessage('导入结束')
      }
    },
  },
}
</script>
<style scoped>
.text-line {
  margin: 10px;
  font-size: 15px;
}
</style>
